package com.donger.common.idempotent.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.donger.common.idempotent.IdempotentProperties;
import com.donger.common.idempotent.execption.IdempotentException;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * IdempotentService
 *
 * @author xyx
 * @date 2020-05-24 18:38
 */
@AllArgsConstructor
public class IdempotentService {

    private final IdempotentProperties properties;
    private final RedisTemplate redisTemplate;

    public String createToken() {
        String token = UUID.fastUUID().toString();
        redisTemplate.opsForValue().set(token, token, properties.getExpireTime(), TimeUnit.MINUTES);
        return token;
    }

    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(properties.getStoreTokenKey());
        if (StrUtil.isBlank(token)) {
            token = request.getParameter(properties.getStoreTokenKey());
            if (StrUtil.isBlank(token)) {
                throw new IdempotentException("非法提交");
            }
        }
        Object tokenVal = redisTemplate.opsForValue().get(token);
        if (Objects.isNull(tokenVal)) {
            throw new IdempotentException("禁止重复提交！");
        }
        Boolean del = redisTemplate.delete(token);
        if (!del) {
            throw new IdempotentException("禁止重复提交！");
        }
    }
}
